﻿using AntdUI;
using SqlSugar;
using SqlSugar.Extensions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Net.Mime.MediaTypeNames;

namespace TPressure
{
    public partial class DeviceManageForm : BaseForm
    {
        #region 属性
        /// <summary>设备
        /// 
        /// </summary>
        private Device obj;

        #endregion

        #region 自定义方法

        /// <summary>设备列表
        /// 
        /// </summary>
        public void LoadDeviceList()
        {
            List<Device> list = SqlSugarHelper.Inquireable<Device>(null);
            UpdateTable(list);
        }

        /// <summary>更新DataGridView
        /// 
        /// </summary>
        /// <param name="list"></param>
        private void UpdateTable(List<Device> list)
        {
            var antItemList = new List<DeviceItem>();
            foreach (Device item in list)
            {
                antItemList.Add(new DeviceItem(item.deviceNumber,item.deviceName,item.deviceAddress,item.portAddress,
                                               item.baudRate,item.di_point_count,item.do_point_count,item.input_register_count,item.holding_register_count));
            }
            Table1.DataSource = antItemList;
        }

        /// <summary>更新模型
        /// 
        /// </summary>
        private void UpdateObject() 
        {
            obj.deviceNumber = DeviceNumberInput.Text.ObjToInt();
            obj.deviceName = DeviceNameInput.Text;
            obj.deviceAddress = DeviceAddressInputNumber.Text.ObjToInt();
            obj.portAddress = PortAddressSelect.Text;
            obj.baudRate = BaudRateSelect.Text.ObjToInt();
            obj.di_point_count = DIPointCountInput.Text.ObjToInt();
            obj.do_point_count = DOPointCOuntInput.Text.ObjToInt();
            obj.input_register_count = InputRegisterCountInput.Text.ObjToInt();
            obj.holding_register_count = HoldingRegisterCountInput.Text.ObjToInt();
        }

        /// <summary>刷新
        /// 
        /// </summary>
        private void Reload()
        {
            DeviceNumberInput.Text = DateTimeOffset.Now.ToUnixTimeSeconds().ToString();
            obj = new Device();
            DeviceNameInput.Text = "";
            DeviceAddressInputNumber.Text = "";
            PortAddressSelect.Text = "";
            BaudRateSelect.Text = "";
        }

        /// <summary>重复检测
        /// 
        /// </summary>
        /// <returns></returns>
        private bool CheckRepeat()
        {
            Dictionary<string, Object> where = new Dictionary<string, Object>();
            where["deviceName"] = DeviceNameInput.Text;
            List<Device> list = SqlSugarHelper.Inquireable<Device>(where);
            int count = list.Count;
            if (count > 0)
            {
                AntdUI.Message.error(this, where["deviceName"] + "设备已存在", Font);
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>根据编号查询记录
        /// 
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        private Device DeviceWithNumber(int number)
        {
            Dictionary<string, Object> where = new Dictionary<string, Object>();
            where["deviceNumber"] = number;
            List<Device> list = SqlSugarHelper.Inquireable<Device>(where);
            if (list.Count > 0)
            {
                return list[0];
            }
            else
            {
                return null;
            }
        }

        /// <summary>判断记录是否存在
        /// 
        /// </summary>
        /// <param name="number"></param>
        private bool CheckSelectedRowExist(int number)
        {
            obj = DeviceWithNumber(number);
            if (obj == null)
            {
                Alert.Error("设备记录不存在", this);
                return false;
            }
            else
            {
                return true;
            }
        }

        #endregion

        #region 系统方法
        public DeviceManageForm()
        {
            InitializeComponent();
        }

        private void DeviceManageForm_Load(object sender, EventArgs e)
        {
            this.Resizable = false;
           Reload();
           Table1.Columns = new AntdUI.ColumnCollection {
                new AntdUI.Column("deviceNumber","编号"){ColAlign=AntdUI.ColumnAlign.Center},
                new AntdUI.Column("deviceName","名称"){ColAlign=AntdUI.ColumnAlign.Center},
                new AntdUI.Column("deviceAddress","地址"){ColAlign=AntdUI.ColumnAlign.Center},
                new AntdUI.Column("portAddress","串口"){ColAlign=AntdUI.ColumnAlign.Center},
                new AntdUI.Column("baudRate","波特率"){ColAlign=AntdUI.ColumnAlign.Center},
                new AntdUI.Column("di_point_count","DI点"){ColAlign=AntdUI.ColumnAlign.Center},
                new AntdUI.Column("do_point_count","DI点"){ColAlign=AntdUI.ColumnAlign.Center},
                new AntdUI.Column("input_register_count","只读点"){ColAlign=AntdUI.ColumnAlign.Center},
                new AntdUI.Column("holding_register_count","读写点"){ColAlign=AntdUI.ColumnAlign.Center},
                new AntdUI.Column("operation","操作"){ Fixed=true,Width="auto",ColAlign=AntdUI.ColumnAlign.Center}
            };
            Spin.Config config = new Spin.Config
            {
                Text = "正在加载中...",
            };
            Table1.Spin(config, () =>
            {
                LoadDeviceList();
            }, () =>
            {
                
            });
        }


        /// <summary>点击表格操作按钮回调
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Table1_CellButtonClick(object sender, TableButtonEventArgs e)
        {
            if (e.Record is DeviceItem data)
            {
                AntdUI.CellLink link = e.Btn;
                if (link.Id == "edit")
                {
                    bool res = CheckSelectedRowExist(data.deviceNumber);
                    if (!res)
                    {
                        return;
                    }
                    DeviceNumberInput.Text = data.deviceNumber.ToString();
                    DeviceNameInput.Text = data.deviceName;
                    DeviceAddressInputNumber.Text = data.deviceAddress.ToString();
                    PortAddressSelect.Text = data.portAddress;
                    BaudRateSelect.Text = data.baudRate.ToString();
                    DIPointCountInput.Text = data.di_point_count.ToString();
                    DOPointCOuntInput.Text = data.do_point_count.ToString();
                    InputRegisterCountInput.Text = data.input_register_count.ToString();
                    HoldingRegisterCountInput.Text = data.holding_register_count.ToString();
                }
                else if (link.Id == "delete")
                {
                    AntdUI.Modal.open(new AntdUI.Modal.Config(this, "您确定要删除此设备吗？", AntdUI.TType.Warn)
                    {
                        OnOk = config =>
                        {
                            bool res = CheckSelectedRowExist(data.deviceNumber);
                            if (!res)
                            {
                                return true;
                            }
                            List<Device> list = new List<Device>();
                            list.Add(obj);
                            int deleteRes = SqlSugarHelper.Deleteable(list);
                            if (deleteRes > 0)
                            {
                                RefreshButton_Click(this.RefreshButton, null);
                            }
                            else
                            {
                                Alert.Error("删除设备失败", this);
                            }
                            return true;
                        },
                    });
                }
                else if (link.Id == "point")
                {
                    DevicePointForm frm = new DevicePointForm();
                    frm.deviceObj = data;
                    frm.ShowDialog();
                }
            }
        }
        #endregion

        #region 点击按钮
        /// <summary>刷新
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RefreshButton_Click(object sender, EventArgs e)
        {
            Reload();
            Task.Run(() =>
            {
                LoadDeviceList();
            });
        }
        
        /// <summary>确定
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void ConfirmButton_Click(object sender, EventArgs e)
        {
            if (obj.deviceNumber > 0)
            {
                if (DeviceNameInput.Text != obj.deviceName)
                {
                    bool repeatRes = CheckRepeat();
                    if (repeatRes)
                    {
                        return;
                    }
                }
                UpdateObject();
                List<Device> list = new List<Device>();
                list.Add(obj);
                int res = SqlSugarHelper.Updateable<Device>(list);
                if (res > 0)
                {
                    RefreshButton_Click(this.RefreshButton, null);
                }
                else
                {
                    Alert.Error("编辑设备失败", this);
                }
            }
            else
            {
                if (DeviceNameInput.Text.Length ==0)
                {
                    Alert.Error("请输入设备名称",this);
                    DeviceNameInput.Focus();
                    return;
                }
                
                if (DeviceAddressInputNumber.Text.Length == 0)
                {
                    Alert.Error("请输入设备地址", this);
                    DeviceAddressInputNumber.Focus();
                    return;
                }

                if (PortAddressSelect.Text.Length == 0)
                {
                    Alert.Error("请选择串口地址", this);
                    PortAddressSelect.Focus();
                    return;
                }

                if (BaudRateSelect.Text.Length == 0)
                {
                    Alert.Error("请选择波特率", this);
                    BaudRateSelect.Focus();
                    return;
                }

                bool repeatRes = CheckRepeat();
                if (repeatRes)
                {
                    return;
                }
                UpdateObject();
                List<Device> list = new List<Device>();
                list.Add(obj);
                int res = SqlSugarHelper.Insertable(list);
                if (res > 0)
                {
                    RefreshButton_Click(this.RefreshButton, null);
                }
                else
                {
                    Alert.Error("添加设备失败", this);
                }
            }
        }

        #endregion
    }
}
